<template>
  <div class="user-list-container" style="padding: 20px">
    <!-- 搜索区域 -->
    <el-form :inline="true" :model="searchForm" style="margin-bottom: 20px">
      <el-form-item label="用户ID">
        <el-input
          v-model="searchForm.id"
          placeholder="请输入用户ID"
          clearable
          style="width: 150px"
          @keyup.enter="handleSearch"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 用户表格 -->
    <el-table
      :data="userList"
      stripe
      style="width: 100%; margin-top: 20px"
      :loading="loading"
    >
      <el-table-column prop="id" label="用户ID" width="80" />
      <el-table-column prop="email" label="邮箱" min-width="160" />
      <el-table-column label="是否VIP">
        <template #default="scope">
          <el-tag :type="getIsVip(scope.row) ? 'success' : 'info'">
            {{ getIsVip(scope.row) ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="jobVipEndTime" label="VIP到期时间" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.jobVipEndTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="freeNum" label="免费查询次数" width="130" />
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            @click="handleEditVip(scope.row)"
          >
            修改VIP
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination" style="margin-top: 20px; text-align: right">
      <el-pagination
        background
        layout="total, prev, pager, next, sizes, jumper"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        v-model:page-size="pageSize"
        v-model:current-page="currentPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 修改VIP对话框 -->
    <el-dialog v-model="dialogVisible" title="修改VIP状态" width="400px">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="用户ID">{{ editForm.id }}</el-form-item>
        <el-form-item label="免费次数">
          <el-input
            v-model.number="editForm.freeNum"
            type="number"
            min="0"
            placeholder="请输入免费次数"
          />
        </el-form-item>
        <el-form-item label="VIP到期时间">
          <el-date-picker
            v-model="editForm.jobVipEndTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择VIP到期时间"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>  
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {getUserApi,updateUserVipApi} from '../../api/System'

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const userList = ref([])

// 搜索表单
const searchForm = ref({
  id: '' // 用户输入的ID
})

// 编辑VIP对话框
const dialogVisible = ref(false)
const editForm = ref({
  id: null,
  freeNum: 0,
  jobVipEndTime: ''
})

// ✅ 核心：获取用户列表（支持分页 + 按ID查询）
const fetchUserList = async () => {
  loading.value = true
  try {
    // 构建请求参数
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value
    }

    const id = searchForm.value.id?.trim()
    // ✅ 只有当 id 是正整数时，才传给后端，避免传 "" 或 "abc"
    if (id && /^\d+$/.test(id)) {
      params.id = parseInt(id, 10)
    }

    const res = await getUserApi(params)

    userList.value = res.data.rows || []
    total.value = res.data.total || 0

    // 如果传了ID但没查到用户
    if (params.id && userList.value.length === 0) {
      ElMessage.warning('未找到该用户')
    }
  } catch (error) {
    console.error('获取用户数据失败', error)
    ElMessage.error('加载数据失败')
    userList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 判断用户是否为 VIP
const getIsVip = (user) => {
  const now = new Date().getTime()

  // 检查 VIP 到期时间：是否大于当前时间
  const hasValidEndTime = user.jobVipEndTime && new Date(user.jobVipEndTime).getTime() > now

  // 检查免费次数
  const hasFreeNum = user.freeNum > 0

  // 只要满足一个条件就是 VIP
  return hasValidEndTime || hasFreeNum
}

// 时间格式化
const formatDateTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  const YYYY = date.getFullYear()
  const MM = String(date.getMonth() + 1).padStart(2, '0')
  const DD = String(date.getDate()).padStart(2, '0')
  const HH = String(date.getHours()).padStart(2, '0')
  const mm = String(date.getMinutes()).padStart(2, '0')
  const ss = String(date.getSeconds()).padStart(2, '0')
  return `${YYYY}-${MM}-${DD}T${HH}:${mm}:${ss}`
}

// 分页事件
const handleSizeChange = () => {
  fetchUserList()
}
const handleCurrentChange = () => {
  fetchUserList()
}

// 搜索与重置
const handleSearch = () => {
  currentPage.value = 1 // 重置页码
  fetchUserList()
}

const handleReset = () => {
  searchForm.value.id = ''
  currentPage.value = 1
  fetchUserList()
}

// 修改VIP
const handleEditVip = (row) => {
  editForm.value = {
    id: row.id,
    freeNum: row.freeNum || 0,
    jobVipEndTime: row.jobVipEndTime || ''
  }
  dialogVisible.value = true
}

// 提交修改
const submitEdit = async () => {
  try {
    editForm.value.jobVipEndTime = formatDateTime(editForm.value.jobVipEndTime)
    const result = await updateUserVipApi(editForm.value)
    if (result.code === 1) {
      ElMessage.success('VIP状态更新成功')
      dialogVisible.value = false
      fetchUserList() // 刷新列表
    }
  } catch (error) {
    console.error('更新VIP失败', error)
    ElMessage.error('更新失败，请重试')
  }
}

// 页面初始化
onMounted(() => {
  fetchUserList()
})
</script>

<style scoped>
/* 可根据需要添加样式 */
</style>